#include "event/znx_worker_proc.h"

void znx_test_dump_handle(znx_event_t *event)
{
    int data = (int)(intptr_t)event->data;
    ZNX_DEF_LOG_DEBUG("timer_task timeout, data: %d", data);

    if (data < 50) {
        data += 10;
        event->data = (void *)(intptr_t)data;
        znx_event_loop_add_timer(event, 5);
        return;
    }

    znx_thread_free(event);
}

void znx_test_timer_handler(znx_dispatch_event_t *dispatch_event)
{
    int data = (int)(intptr_t)dispatch_event->data;
    znx_thread_free(dispatch_event);

    znx_event_t *timer_event = znx_thread_calloc(sizeof(znx_event_t));
    timer_event->handler = znx_test_dump_handle;
    timer_event->data = (void *)(intptr_t)data;

    znx_event_loop_add_timer(timer_event, 5);
}

void test_timer_task(int i)
{
    znx_dispatch_event_t *dispatch_event =
        znx_thread_calloc(sizeof(znx_dispatch_event_t));
    dispatch_event->handler = znx_test_timer_handler;
    dispatch_event->data = (void *)(intptr_t)i;
    znx_worker_processor_post_event(dispatch_event);
}

int main()
{
    znx_def_log_init(0, LOG_LEVEL_DEBUG, NULL, LOG_ROLLING_DAY);
    znx_worker_processor_init();
    znx_worker_processor_start(5, 1, 1);

    for (int i = 0; i < 9; i++) {
        test_timer_task(i);
    }

    proc_exit = ZNX_TRUE;

    while (!znx_worker_processor_all_task_done()) {
        usleep(10000);
    }

    znx_worker_processor_stop();

    return 0;
}
